package com.lx.api.utils;

import com.lx.core.weight.entity.dto.WeightPageDTO;
import com.lx.core.weight.entity.vo.WeightPageList;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;

public class ListExcelExporter {
    /**
     * 设置响应头
     */
    public static void setResponseHeaders(HttpServletResponse response, String fileName) throws IOException {
        // 强制指定为 Excel 类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");

        // 兼容性更好的文件名编码
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        // 禁用缓存
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }

    private static void createCellWithStyle(Row row, int column, Object value, CellStyle style) {
        Cell cell = row.createCell(column);

        if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Number) {
            cell.setCellValue(((Number) value).doubleValue());
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else {
            cell.setCellValue(value != null ? value.toString() : "");
        }

        cell.setCellStyle(style);
    }

    /**
     * 生成Excel文件
     */
    public static void generateExcel(HttpServletResponse response, List<WeightPageList> dataList, WeightPageDTO dto) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("重量数据");
            // 创建表头
            createHeaderRow(sheet, workbook);

            // 填充数据
            fillDataRows(sheet, dataList, workbook);

            // 自动调整列宽
            autoSizeColumns(sheet);

            // 写入响应流
            workbook.write(response.getOutputStream());
           // response.flushBuffer();
        }
    }

    /**
     * 创建表头行
     */
    public static void createHeaderRow(Sheet sheet, Workbook workbook) {
        Row headerRow = sheet.createRow(0);
        CellStyle headerStyle = createHeaderStyle(workbook);

        String[] headers = {
                "流水号", "姓名", "货物名称", "毛重","毛重称重时间", "毛重地磅",
                "皮重","皮重称重时间", "皮重地磅","净重", "单价(元)", "总价(元)","过磅费(元)","是否结算"
        };

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }
    }

    /**
     * 填充数据行
     */
    public static void fillDataRows(Sheet sheet, List<WeightPageList> dataList, Workbook workbook) {
        if (dataList == null || dataList.isEmpty()) {
            return;
        }

        CellStyle dateStyle = createDateStyle(workbook);
        CellStyle dataStyle = createDataStyle(workbook); // 创建数据样式
        for (int i = 0; i < dataList.size(); i++) {
            WeightPageList item = dataList.get(i);
            Row row = sheet.createRow(i + 1);

            int colIndex = 0;
            createCellWithStyle(row,colIndex++,item.getNo() != null ? item.getNo() : "",dataStyle);
            createCellWithStyle(row,colIndex++,item.getName() != null ? item.getName() : "",dataStyle);
            createCellWithStyle(row,colIndex++,item.getGoodsName() != null ? item.getGoodsName() : "",dataStyle);
            createCellWithStyle(row, colIndex++, item.getGross() != null ? item.getGross().intValue() : 0, dataStyle);
            // 日期字段特殊处理
            Cell dateCell = row.createCell(colIndex++);
            if (item.getGrossCreateTime() != null) {
                dateCell.setCellValue(item.getGrossCreateTime());
                dateCell.setCellStyle(dateStyle);
            } else {
                dateCell.setCellValue("");
                dateCell.setCellStyle(dateStyle);
            }
            createCellWithStyle(row, colIndex++, item.getGrossNumberName() != null ? item.getGrossNumberName() : "", dataStyle);
            createCellWithStyle(row, colIndex++, item.getTare() != null ? item.getTare().intValue() : 0, dataStyle);
            // 日期字段特殊处理
            Cell tareDateCell = row.createCell(colIndex++);
            if (item.getTareCreateTime() != null) {
                tareDateCell.setCellValue(item.getTareCreateTime());
                tareDateCell.setCellStyle(dateStyle);
            } else {
                tareDateCell.setCellValue("");
                tareDateCell.setCellStyle(dateStyle);
            }
            createCellWithStyle(row, colIndex++, item.getTareNumberName() != null ? item.getTareNumberName() : "", dataStyle);
            createCellWithStyle(row, colIndex++, item.getNet() != null ? item.getNet().intValue() : 0, dataStyle);
            DecimalFormat df = new DecimalFormat("0.00");
            String price="";
            if(item.getPrice()!=null)
            {
                price=df.format(item.getPrice().doubleValue());
            }
            createCellWithStyle(row, colIndex++, price, dataStyle);
            createCellWithStyle(row, colIndex++, item.getTotal(), dataStyle);
            createCellWithStyle(row, colIndex++, item.getWeightFee(), dataStyle);
            createCellWithStyle(row, colIndex, item.getSettlement() == 0 ? "否" : "是", dataStyle);
        }
    }

    /**
     * 创建表头样式
     */
    public static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();

        font.setBold(true);
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setFontHeightInPoints((short) 12);

        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        return style;
    }

    /**
     * 创建数据样式
     */
    public static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        return style;
    }

    /**
     * 创建日期样式
     */
    public static CellStyle createDateStyle(Workbook workbook) {
        CellStyle style = createDataStyle(workbook);
        CreationHelper createHelper = workbook.getCreationHelper();

        style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        return style;
    }

    /**
     * 自动调整列宽
     */
    public static void autoSizeColumns(Sheet sheet) {
        int columnCount = 9; // 根据表头列数调整
        for (int i = 0; i < columnCount; i++) {
            sheet.autoSizeColumn(i);
            // 设置最小列宽
            sheet.setColumnWidth(i, Math.max(sheet.getColumnWidth(i), 3000));
        }
    }

    /**
     * 处理导出错误
     */
    public static void handleExportError(HttpServletResponse response, Exception e) throws IOException {
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        String errorMessage = "导出失败: " + e.getMessage();
        response.getWriter().write("{\"code\": 500, \"message\": \"" + errorMessage + "\"}");
    }
}
